import React from 'react';
import { getUserInfo } from '@/utils';
// import { Modal, message } from 'antd';
import { connect, Redirect } from 'umi';
import { PageLoading } from '@ant-design/pro-layout';

// const { confirm } = Modal;

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };
  componentDidMount() {
    // const { dispatch } = this.props;
    const currentUser = getUserInfo();
    this.setState({
      isReady: true,
    });

    // 判断是否存在缓存
    if (currentUser) {
      // 获取用户权限菜单信息
      // dispatch({
      //   type: 'login/fetchGetUserDetailByUserId',
      //   payload: currentUser?.id,
      //   callback: (res) => {
      //     if (res && (res.code || res.msg)) {
      //       return;
      //     }
      //     if (res) {
      //       dispatch({
      //         type: 'login/fetchGetUserMenu',
      //         payload: res?.id,
      //       });
      //     } else {
      //       message.error('当前用户没有权限！');
      //     }
      //   },
      // });
    }
  }
  render() {
    const { isReady } = this.state;
    const { children, loading } = this.props;
    const currentUser = getUserInfo(); // 用户存储信息

    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const isHasLocal = currentUser && currentUser.user.id;

    if (!window.__POWERED_BY_QIANKUN__ && (loading || (!isHasLocal && loading) || !isReady)) {
      return <PageLoading tip="loading" />;
    }

    if (!isHasLocal && window.location.pathname !== '/user/login') {
      if (window.__POWERED_BY_QIANKUN__) {
        const str = window.location.href;
        const arr = str.split('#')?.[0]?.split('/');
        const indexHome = arr.indexOf('home');
        const path = arr.splice(indexHome, 2).join('/');
        window.location.href = `/${path}/#/user/login`;
        message.error('登录失效，请重新登录');
      } else {
        return <Redirect to="/user/login" />;
      }
    }

    return children;
  }
}
export default connect(({ loading }) => ({
  loading: loading.models.login,
}))(SecurityLayout);
